﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.Security.AccessControl;

namespace MediaPortal.Plugins
{

    [Serializable]
    public class TVProgramList
    {

        //public static string theFile="C:\\Program Files\\MillieSoft\\TunerFreeMCE\\programList.dat";
        public List<TVProgram> thePrograms;
        public List<TVProgramLite> theProgramNames;
        public DateTime oldestBBCProg, oldestPossibleBBCProg;
        public DateTime oldestITVProg, oldestPossibleITVProg;
        public DateTime oldestC4Prog, oldestPossibleC4Prog;
        string theFile,theFile2;
        public Boolean isLoaded,programNamesIsLoaded;
        string _cacheOverride;

        public TVProgramList()
        {
            init("");
        }
        public TVProgramList(string cacheOverride)
        {
            init(cacheOverride);
        }
            public void init(string cacheOverride){
            _cacheOverride = cacheOverride;
            thePrograms=new List<TVProgram>();
            isLoaded = false;
            programNamesIsLoaded = false;
            if (cacheOverride == "")
            {
                theFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal\\iPlayer\\programList.dat";
                theFile2 = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal\\iPlayer\\programNames.dat";
            }
            else
            {
                theFile = cacheOverride;
            }
        }

        public void Add(TVProgram program)
        {
            thePrograms.Add(program);
        }

        public void LoadFromFile()
        {

            try
            {

                oldestBBCProg = DateTime.Now.AddYears(-1);
                oldestPossibleBBCProg = DateTime.Now.Date.AddDays(-7);

                oldestITVProg = DateTime.Now.AddYears(-1);
                oldestPossibleITVProg = DateTime.Now.Date.AddMonths(-1).AddDays(1);

                oldestC4Prog = DateTime.Now.AddYears(-1);
                oldestPossibleC4Prog = DateTime.Now.Date.AddMonths(-1).AddDays(1);

                Boolean fileFound = false;

                if (File.Exists(theFile))
                {
                    Stream fileStream = File.Open(theFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    XmlSerializer f1 = new XmlSerializer(typeof(List<TVProgram>));
                    Object o1 = f1.Deserialize(fileStream);
                    thePrograms = (List<TVProgram>)o1;
                    fileStream.Close();


                    foreach (TVProgram p1 in thePrograms)
                    {
                      /** Clean these up in the BBC program provider
                       * if (p1.ProgramProvider == "BBC" && p1.ProgramDate > oldestBBCProg)
                            if (p1.ProgramProvider == "BBC" && p1.ProgramDate > oldestBBCProg)
                            {
                            oldestBBCProg = p1.ProgramDate;
                        }
                        */
                        if (p1.ProgramProvider == "ITV" && p1.ProgramDate > oldestITVProg)
                        {
                            oldestITVProg = p1.ProgramDate;
                        }

                        if (p1.ProgramProvider == "C4" && p1.ProgramDate > oldestC4Prog)
                        {
                            oldestC4Prog = p1.ProgramDate;
                        }

                    }
                    oldestBBCProg = oldestBBCProg.AddDays(-1);
                    oldestITVProg = oldestITVProg.AddDays(-1);
                } 
            }
            catch (Exception e) 
            {

            }
            isLoaded = true;
        }
        public void loadNamesFromFile(){

            if (File.Exists(theFile2))
            {
                Stream fileStream2 = File.Open(theFile2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer f2 = new XmlSerializer(typeof(List<TVProgramLite>));
                Object o2 = f2.Deserialize(fileStream2);
                theProgramNames = (List<TVProgramLite>)o2;
                fileStream2.Close();
            }
            programNamesIsLoaded = true;

        }

        public void WriteToFile()
        {
            Stream fileStream;
            if (File.Exists(theFile))
            {
                fileStream = File.Open(theFile, FileMode.Create, FileAccess.Write, FileShare.Read);
            }
            else
            {
                if (_cacheOverride != "")
                {
                    string theDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal";
                    if (!Directory.Exists(theDir))
                    {
                        Directory.CreateDirectory(theDir);
                    }
                    theDir += "\\iPlayer";
                    if (!Directory.Exists(theDir))
                    {
                        Directory.CreateDirectory(theDir);
                    }
                }


                fileStream = File.Create(theFile);
                FileSecurity fileSec = File.GetAccessControl(theFile);
                fileSec.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
                File.SetAccessControl(theFile, fileSec);
            }

            XmlSerializer f1 = new XmlSerializer(typeof(List<TVProgram>));
            f1.Serialize(fileStream, thePrograms);
            fileStream.Close();


            thePrograms.Sort(delegate(TVProgram p1, TVProgram p2) { return p1.ProgramName.CompareTo(p2.ProgramName); });
            string previousProgram = "";
            theProgramNames = new List<TVProgramLite>();
            thePrograms.ForEach(delegate(TVProgram p1)
            {
                if (p1.ProgramName != previousProgram)
                {
                    TVProgramLite newProgram = new TVProgramLite(p1.ProgramName);
                    theProgramNames.Add(newProgram);
                    previousProgram = p1.ProgramName;
                }
            });

            theFile2 = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal\\iPlayer\\programNames.dat";

            Stream fileStream2;
            if (File.Exists(theFile2))
            {
              fileStream2 = File.Open(theFile2, FileMode.Create, FileAccess.Write, FileShare.Read);
            }
            else
            {
                fileStream2 = File.Create(theFile2);
                FileSecurity fileSec2 = File.GetAccessControl(theFile2);
                fileSec2.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
                File.SetAccessControl(theFile2, fileSec2);
            }


            XmlSerializer f2 = new XmlSerializer(typeof(List<TVProgramLite>));
            f2.Serialize(fileStream2, theProgramNames);
            fileStream2.Close();

        }
    }

    [Serializable]
    public class TVProgramLite
    {
        private string _programName;
        public TVProgramLite()
        {
            _programName = "";
        }

        public TVProgramLite(string programName)
        {
            _programName = programName;
        }
        public string pn
        {
            set
            {
                _programName = value;
            }
            get
            {
                return _programName;
            }
        }
    }

        [Serializable]
    public class TVProgram
    {
        private string _programName;
        private string _programLink;
        private string _programEpisode;
        private string _programSummary;
        private string _programImage;
        private string _programId;
        private string _programProvider;
        private string _programGenre;
        private string _channel;
        private string _channelLogoURL;
        private DateTime _programDate;
        public List<String> Categories;

        public TVProgram()
        {
            _programName = "";
            _programLink = "";
            _programEpisode = "";
            _programSummary = "";
            _programImage = "";
            _programId = "";
            _programGenre = "";
            _channel = "";
            _channelLogoURL = "";
            _programDate = new DateTime();
            _programProvider = "";
            Categories = new List<string>();
        }

        public TVProgram(string programId)
        {
            _programId = programId;
            _programName = "";
            _programLink = "";
            _programEpisode = "";
            _programSummary = "";
            _programImage = "";
            _programGenre = "";
            _channel = "";
            _channelLogoURL = "";
            _programDate = new DateTime();
            _programProvider = "BBC";
            Categories = new List<string>();

            /* HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.bbc.co.uk/iplayer/metafiles/episode/" + programId + ".xml");
             myRequest.Method = "GET";
             WebResponse myResponse = myRequest.GetResponse();
             StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
             string result = sr.ReadToEnd();
             sr.Close();
             myResponse.Close();
             StringReader s1 = new StringReader(result);
             XmlDocument iPlayerEpisode = new XmlDocument();
             iPlayerEpisode.Load(s1);
             _programName = iPlayerEpisode.SelectSingleNode("/iplayerMedia/concept/title").InnerText;
             _programEpisode = iPlayerEpisode.SelectSingleNode("/iplayerMedia/concept/longSynopsis").InnerText;
             _programLink = "file:///C:\\Program Files\\Milliesoft\\iPlayer\\iPlayer.htm?id=" + programId + "&title=" + System.Web.HttpUtility.UrlPathEncode(_programName) + "&episode=" + System.Web.HttpUtility.UrlPathEncode(_programEpisode);
             _programImage = iPlayerEpisode.SelectSingleNode("/iplayerMedia/concept/thumbnail/url").InnerText;*/

        }
        public TVProgram(TVProgram program)
        {
            _programName = program.ProgramName;
            _programLink = program.ProgramLink;
            _programEpisode = program.ProgramEpisode;
            _programSummary = program.ProgramSummary;
            _programImage = program.ProgramImage;
            _programProvider = program.ProgramProvider;
            _programGenre = program.ProgramGenre;
            _programDate = program.ProgramDate;
            _channelLogoURL = program.ChannelLogoURL;
            _channel = program.Channel;
            Categories = program.Categories;

            _programId = program.ProgramId;
        }
        public TVProgram(string programName, string programLink, string programEpisode, string programImage, string programSummary, string programProvider, string programGenre, DateTime programDate, string channel, string channelLogoURL, string programId)
        {
            _programName = programName;
            _programLink = programLink;
            _programEpisode = programEpisode;
            _programSummary = programSummary;
            _programImage = programImage;
            _programProvider = programProvider;
            _programGenre = programGenre;
            _programDate = programDate;
            _channelLogoURL = channelLogoURL;
            _channel = channel;
            Categories = new List<string>();

            _programId = programId;
        }

         public Boolean hasCategory(string category){
            Boolean _hasCategory=false;
            foreach (string currentCat in Categories)
            {
                if (currentCat==category){
                    _hasCategory=true;
                    break;
                }
            }
             return _hasCategory;
         }

        public string ProgramId
        {
            get
            {
                return _programId;
            }
            set
            {
                _programId = value;
            }
        }
        public string ProgramName
        {
            get
            {
                return _programName;
            }
            set
            {
                _programName = value;
            }
        }
        public string ProgramLink
        {
            get
            {
                return _programLink;
            }
            set
            {
                _programLink = value;
            }
        }
        public string ProgramEpisode
        {
            get
            {
                return _programEpisode;
            }
            set
            {
                _programEpisode = value;
            }
        }
        public string ProgramImage
        {
            get
            {
                return _programImage;
            }
            set
            {
                _programImage = value;
            }
        }
        public string ProgramSummary
        {
            get
            {
                return _programSummary;
            }
            set
            {
                _programSummary = value;
            }
        }
        public string ProgramProvider
        {
            get
            {
                return _programProvider;
            }
            set
            {
                _programProvider = value;
            }
        }
        public string ProgramGenre
        {
            get
            {
                return _programGenre;
            }
            set
            {
                _programGenre = value;
            }
        }
        public DateTime ProgramDate
        {
            get
            {
                return _programDate;
            }
            set
            {
                _programDate = value;
            }
        }
        public string Channel
        {
            get
            {
                return _channel;
            }
            set
            {
                _channel = value;
            }
        }
        public string ChannelLogoURL
        {
            get
            {
                return _channelLogoURL;
            }
            set
            {
                _channelLogoURL = value;
            }
        }

        public int DateCompareTo(TVProgram p2)
        {
            if (p2.ProgramProvider.Equals("ITV") && ProgramProvider.Equals("ITV"))
            {
                if (ProgramDate.Equals(p2.ProgramDate))
                {
                    return (ProgramId.CompareTo(p2.ProgramId));
                }
                else
                {
                    return ProgramDate.CompareTo(p2.ProgramDate);
                }
            }
            else if (p2.ProgramProvider.Equals("C4") && ProgramProvider.Equals("C4"))
            {
                if (ProgramDate.Equals(p2.ProgramDate))
                {
                    return (ProgramId.CompareTo(p2.ProgramId));
                }
                else
                {
                    return ProgramDate.CompareTo(p2.ProgramDate);
                }
            }
            else if (p2.ProgramProvider.Equals("Five") && ProgramProvider.Equals("Five"))
            {
                if (ProgramDate.Equals(p2.ProgramDate))
                {
                    return (ProgramId.CompareTo(p2.ProgramId));
                }
                else
                {
                    return ProgramDate.CompareTo(p2.ProgramDate);
                }
            }
            else
            {
                return ProgramDate.CompareTo(p2.ProgramDate);
            }
        }
    }
}


